/** 공통 메세지 */
var MSG_C			= "등록하시겠습니까?";
var MSG_U			= "수정하시겠습니까?";
var MSG_D			= "삭제하시겠습니까?";

var MSG_REGISTER	= "등록하시겠습까?";
var MSG_SAVE		= "저장하시겠습까?";
var MSG_SAVED		= "저장되었습니다";
var MSG_UPDATE		= "수정하겠습니까?";
var MSG_UPDATED		= "수정되었습니다.";
var MSG_DELETE		= "삭제하시겠습니까?";
var MSG_DELETED		= "삭제되었습니다";
var MSG_REQUIRED	= "필수항목입니다";
var MSG_LOGIN		= "로그인 하시겠습니까?";

var MSG_PROCESS		= "처리하시겠습니까?";
var MSG_PROCESSED	= "처리되었습니다.";
var MSG_SEND		= "발송하시겠습니까?";
var MSG_SENDED		= "발송되었습니다.";
var MSG_DOC			= "서류접수하시겠습니까?";
var MSG_DOCED		= "서류접수 되었습니다.";
var MSG_INSPECT		= "심사중 처리하시겠습니까?";
var MSG_INSPECTED	= "심사중 처리되었습니다.";
var MSG_CONFIRM		= "확인 처리하시겠습니까?";
var MSG_CONFIRMED	= "확인 처리되었습니다.";
var MSG_APPROVE		= "승인 처리하시겠습니까?";
var MSG_APPROVED	= "승인 처리되었습니다";
var MSG_REJECT		= "반려 처리하시겠습니까?";
var MSG_REJECTED	= "반려 처리되었습니다.";
var MSG_CANCEL		= "취소 처리하시겠습니까?";
var MSG_CANCELED	= "취소 처리되었습니다.";

var MSG_REQUEST 	= "신청하시겠습니까?";
var MSG_REQUESTED 	= "신청되었습니다.";

var MSG_SMS			= "SMS를 발송하시겠습니까?";
var MSG_SMSED		= "SMS를 발송하였습니다.";
var MSG_USEROUT		= "탈퇴하시겠습니까?";
var MSG_USEROUTED	= "탈퇴처리되었습니다.";


/**
 * 메세지를 보여준다.
 * @param msgcd		메세지코드
 */
function cfShowMessage(msgcd) {
	if (msgcd == undefined || msgcd == "") {
		//pass
	} else {
		alert(msgcd);
	}
}

function nvl(str, rep) {
	if (str == undefined || str == null || str == "") {
		return rep == undefined ? "" : rep;
	} else {
		return str;
	}
}

function cfOpen(url, t, w, h) {
	var sw = (screen.width - w) / 2;
	var sh = (screen.height - h) / 2;
	return window.open(url, t, 'Width='+w+'px, Height='+h+'px, Left='+sw+', Top='+sh+',resizable=yes,scrollbars=yes').focus();
}


function cfCheckLogin(isLogin) {
	if (!isLogin) {
		if (confirm(MSG_LOGIN)) {
			document.location.href = "/home/help/login.jsp";
		}
	}
	return isLogin;
}

//Form Invalid Check
function cfCheckRequired(oObj, msg, bFocus) {
	if (bFocus == undefined) {
		bFocus = true;
	}

	var strValue = "";
	if ($(oObj).is('input:radio')) {
		$(oObj).each(function() {
			if (this.checked) {
				strValue = this.value;
			}
		});
		bFocus = false;
	} else if ($(oObj).is('select')) {
		strValue = $(oObj).val();
	} else {
		strValue = $(oObj).val();
	}
	
	
	if (strValue == '') {
		alert(msg);
		if (bFocus) {
			oObj.focus();
		}
		return false;
	}
	return true;
}



//Form Invalid Check
function cfCheckLength(oObj, len, msg, bFocus) {
	if (bFocus == undefined) {
		bFocus = true;
	}

	var strValue = $(oObj).val();

	if (strValue.length < len) {
		alert(msg);
		if (bFocus) {
			oObj.focus();
		}
		return false;
	}
	return true;
}



function cfCheckSame(oObj1, oObj2, msg) {
	if ($(oObj1).val() != $(oObj2).val()) {
		alert(msg);
		$(oObj2).select();
		return false;
	}
	return true;
}


/**
 * 인쇄화면 팝업
 * url   : '/amdin/mnt/cargePrint.do'
 * param :  'SEQ', '2', 'YEAR', '2009', ...
 */
function cfPrint(){
	if( arguments.length < 1 && parseInt(arguments.length % 2) != 1 ) {
		alert("parameter error!");
		return;
	}

	var param = arguments.length > 1 ? "?" : "";
	for(var i = 1; i < arguments.length; i += 2) {//2번째부터 페어로 레포트에 넘길 name=value 값
		param += (arguments[i] + "=" + arguments[i+1])+"&";
	}

	window.open(arguments[0] + param);
}



/***
 * 해당 스트링이 날짜타입인지 체크
 * @param dateStr 원본문자열(2012-03-06, 2012.03.06)
 * @return
 */
function isDate(dateStr) {
	if( dateStr == null || dateStr == '' || dateStr.indexOf('_')>=0 ) return false;

	var datePat = /^(\d{4})(\/|.|)(\d{1,2})(\/|.|)(\d{1,2})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		alert("날짜형식을 확인하세요.  1999.12.31");
		return false;
	}

	year   = matchArray[1];
	month  = matchArray[3]; // p@rse date into variables
	day    = matchArray[5];
	var date = new Date();

	if( year < 1900 || year > 2999){
		alert("년도는 1900~2999 사이로 입력하세요.");
		return false;
	}

	if (month < 1 || month > 12) { // check month range
		alert("날짜의 월은  1 ~ 12 사이입니다.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("날짜의 일은  1 ~ 31 사이입니다.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert(month+"월은 31일이 없습니다.");
		return false;
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			alert( year + "년 2월은 " + day + "일이 없습니다.");
			return false;
		}
	}
	return true; // date is valid
}

function cfValidEmail(value) {
	var result = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
	if (result==false) {
		alert("이메일 형식이 아닙니다.");
		return false;
	}
}




function cfCheckAll() {
	$('input:checkbox[name="chk"]').attr("checked", $("#chkAll").attr("checked") == "checked" ? true : false);
}

//row 추가
function cfaddRow(tid, str, cnt) {
	var lengthcnt=document.getElementById(cnt).value;
	var oTable = document.getElementById(tid);
	var rowLength = oTable.rows.length;
	var oCell;

	//가장 마지막에 행 추가
	var oRow = oTable.insertRow(rowLength);
	oRow.idName = "newTr" + lengthcnt;
	document.getElementById(cnt).value = eval(lengthcnt)+1;

	var lastRow = oTable.rows[rowLength-1];

	if (str=="") {
		//바로 위의 행을 복사

		for (var i=0; i<lastRow.cells.length; i++) {
			oCell = oRow.insertCell(i);
			oCell.innerHTML = lastRow.cells[i].innerHTML;

		}
	} else {


		var str_s = str.split("||");
		for (var i=0; i<lastRow.cells.length; i++) {
			oCell = oRow.insertCell(i);
			oCell.innerHTML = str_s[i];
		}
	}
}
//row삭제
function cfdelRow(tid, row_index) {
	var lo_table = document.getElementById(tid);
		for (var i = 0; i < lo_table.rows.length; i++) {
			if (row_index == lo_table.rows[i].idName)
			lo_table.deleteRow(i);
		}

	 //lo_table.deleteRow(document.getElementById(row_index));
}





//테이블의 row를 합친다
function func_row_merge_Item(tab_obj, start_row, col, stand_col)
{
	var stand_item = "@@";
	var itemCnt = 0;

	if( tab_obj != null)
	{
		for( var row = start_row; row < tab_obj.rows.length ; row++)
		{
			var this_item = "";
			//for (var i = 0; i <= col; i++) {
				//this_item += tab_obj.rows[row].cells[i].innerText;
			//}

			this_item = tab_obj.rows[row].cells[col].innerText + tab_obj.rows[row].cells[stand_col].innerText;

			//item merge 처리
			if (this_item != stand_item) {
				//이전 item merge
				if (itemCnt > 1) {
					tab_obj.rows[row-itemCnt].cells[col].rowSpan = itemCnt;
				}
				//새로운 item 처리
				stand_item = this_item;
				itemCnt = 0;
			}
			else{
				tab_obj.rows[row].deleteCell(col);
			}
			itemCnt++;
		} //end for

		if( itemCnt > 1)
		{
			var row = tab_obj.rows.length;
			tab_obj.rows[row-itemCnt].cells[col].rowSpan = itemCnt;
		}
	}
}

//테이블의 col를 합친다
function func_col_merge_Item(tab_obj, start_col, end_col, stand_val)
{
	var stand_item = "@@";
	var itemCnt = 0;

	if( tab_obj != null)
	{
		for( var row = 0; row < tab_obj.rows.length ; row++)
		{
			var this_item = "";
			for (var col=0; col < tab_obj.rows[row].cells.length; col++) {
				this_item = tab_obj.rows[row].cells[col].innerText;
				if (this_item==stand_val) {
					for (var dcol=start_col+1; dcol<end_col;dcol++) {
						tab_obj.rows[row].deleteCell(start_col+1);
					}
					tab_obj.rows[row].cells[start_col].colSpan = end_col;
				}
			}
		} //end for
	}
}

/**
 * 확장자 체크
 * sllim 20120-03-29
 * @param path $('input:file').val()
 * @param typ  허용될 파일확장자배열 ['jpg','png', 'gif', 'bmp']
 * @returns
 */
function cfTypeCheck(path, typ) {
	var match = false;
	var ext   = ['jpg','png', 'gif', 'bmp'];//default

	var lastidx = -1;
    lastidx = path.lastIndexOf('.');
    var extension = path.substring(lastidx+1, path.length);

    if(typ!=null && typ instanceof Array){ ext = typ }

    for(var i=0;i<ext.length;i++){
    	if((lastidx != -1) && (extension.toLowerCase() == ext[i])){
	    	match = true;
	    }
    }
    return match;
}

/**
 * 값을 설정한다.
 *
 * ex)
 * RADIO 			: $('input:radio[name="offitype"]').setValue('1');
 * SPAN, 기타 INPUT 	: $("#name").setValue("이규식");
 */
$.fn.extend({
	setValue : function(data) {
		if ($(this).is('input:radio')) {
			$(this).each(function() {
				if ($(this).val() == data) {
					$(this).attr("checked", true);
				}
			});
		} else if ($(this).is('input') || $(this).is('select')) {
			$(this).val(data);
		} else {
			$(this).text(data);
		}
		return $(this);
	}
});


/**
 * 숫자만 입력가능하게 한다.
 *
 */
$.fn.extend({
	numeric : function(data) {
		$(this).css("ime-mode","disabled").keypress(function(event){
			if (event.which && (event.which  > 47 && event.which  < 58 || event.which == 8 || event.which == 13)) {
				//pass
			} else {
				event.preventDefault();
			}
		});

		return $(this);
	},
	lowercase : function(data) {
		$(this).css("ime-mode","disabled").keypress(function(event){
			if (event.which && (event.which  > 96 && event.which  < 123 || event.which == 8 || event.which == 13)) {
				//pass
			} else {
				event.preventDefault();
			}
		});
	}
});


/**
 * 날짜 Object의 포맷설정
 * new Date().format('yyyy.MM.dd') -> 2012.01.02
 */
Date.prototype.format = function(f) {
    if (!this.valueOf()) return " ";

    var weekName = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];
    var d = this;

    return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|a\/p)/gi, function($1) {
        switch ($1) {
            case "yyyy": return d.getFullYear();
            case "yy": return (d.getFullYear() % 1000).zf(2);
            case "MM": return (d.getMonth() + 1).zf(2);
            case "dd": return d.getDate().zf(2);
            case "E": return weekName[d.getDay()];
            case "HH": return d.getHours().zf(2);
            case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case "mm": return d.getMinutes().zf(2);
            case "ss": return d.getSeconds().zf(2);
            case "a/p": return d.getHours() < 12 ? "오전" : "오후";
            default: return $1;
        }
    });
};
String.prototype.string = function(len){var s = '', i = 0; while (i++ < len) { s += this; } return s;};
String.prototype.zf = function(len){return "0".string(len - this.length) + this;};
Number.prototype.zf = function(len){return this.toString().zf(len);};



/******************************************************
 *  Function명 : insertDotDate(str)
 *  설      명 : 숫자형식을 받아 콤마를 포함하여 리턴
 *  Parameter  : str     : 현재 숫자 객체(20041212, 981221)
 *  Return     : 값
 *  비      고 : insertDotDate를 내부적으로 call한다.
 ******************************************************/
function toDate(str) {
	if(str==null || str=='') {
		return '';
	}else{
	    var txt = '' + str;//문자열화

	    if(txt.length == 6){
	    	txt = txt.substring(0,2)+'.'+txt.substring(2,4)+'.'+txt.substring(4,6);
	    }else if(txt.length == 8){
	    	txt = txt.substring(0,4)+'.'+txt.substring(4,6)+'.'+txt.substring(6,8);
	    }

	    return txt;
	}
}

//주민번호 체크 함수
function isSSN(s1, s2) {
    n = 2;
    sum = 0;

    if (s2=='') {//만약에 s1에 모든 주민번호가 다 넘어올경우
    	var ssn;
    	ssn = s1.replace("-","");
    	s1 = ssn.substr(0,6);
    	s2 = ssn.substr(6,13);
    }

    for (var i=0; i<s1.length; i++)
            sum += parseInt(s1.substr(i, 1)) * n++;
    for (var i=0; i<s2.length-1; i++) {
            sum += parseInt(s2.substr(i, 1)) * n++;
            if (n == 10) n = 2;
    }
    c = 11 - sum % 11;
    if (c == 11) c = 1;
    if (c == 10) c = 0;
    if (c != parseInt(s2.substr(6, 1))) return false;
    else return true;
}


//쿠키를 저장한다.
function saveCookie(name, value, expiredays)
{
	var today = new Date();
	today.setDate( today.getDate() + expiredays );
	document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + today.toGMTString() + ";"
}

//쿠키를 가저온다.
function getCookie(cookieName)
{
	var cook = document.cookie + ";";
	var idx = cook.indexOf(cookieName, 0);
	var val = "";

	if(idx != -1)
	{
		cook = cook.substring(idx, cook.length);
		begin = cook.indexOf("=", 0) + 1;
		end = cook.indexOf(";", begin);
		val = unescape( cook.substring(begin, end) );
	}

	return val;
}





/**
* Time 스트링을 자바스크립트 Date 객체로 변환
* parameter time: Time 형식의 String
*/
function stringToDate(time) { //parseTime(time)
    var year  = time.substr(0,4);
    var month = time.substr(4,2) - 1; // 1월=0,12월=11
    var day   = time.substr(6,2);

    return new Date(year,month,day);
}



/* 증명사진 업로드 */
function cfUploadUserPic() {
    //starting setting some animation when the ajax starts and completes
    $("#file_upload").closest('th').ajaxStart(function(){
					            $(this).showLoading();
					        	})
						        .ajaxComplete(function(){
						            $(this).hideLoading();
						        });

    $.ajaxFileUpload({
        url:'/common/uploadUserPic.do?userseq=' + $('#userseq').val(),
        secureuri:false,
        fileElementId:'file',
        dataType: 'json',
        success: function (data, status){
        	$('#user_image').attr('src','/common/download.do?fileseq='+data.fileseq);
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function cfPrintHtml(pa) {
	win = window.open();
	win.document.open();
	win.document.write('<'+'html'+'><head'+'><'+'style'+'>');
	win.document.write('@page rotated {size:landscape;}');
	win.document.write('body, td {font-family: Verdana;font-size:10pt;}');
	win.document.write('button {display:none;}');
	win.document.write('<'+'/'+'style'+'>');
	win.document.write('<'+'link rel="stylesheet" type="text/css" href="/css/default.css"'+'/>');
	win.document.write('<'+'link rel="stylesheet" type="text/css" href="/css/admin.css"'+'/>');
	win.document.write('<'+'/'+'head'+'>'+'<'+'body'+'>');
	win.document.write(pa);
	win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
	win.document.write('<'+'script'+''+'>window.print();');
	win.document.write('<'+'/'+'script'+'>');
	//win.print();
}

function cfInitSE(id) {
	nhn.husky.EZCreator.createInIFrame({
		oAppRef: oEditors,
		elPlaceHolder: id,
		sSkinURI: "/SE2.3.1.O9858/SmartEditor2Skin.html",
		fCreator: "createSEditor2",
		htParams : {
			fOnBeforeUnload : function(){}
		}
	});
}

function cfShowModal(message) {
	//select all the a tag with name equal to modal
	//$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		//e.preventDefault();
		
		//Get the A tag
		//var id = $(this).attr('href');
		
		$('#dialog p').text(message);
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').show();
		$('#mask').css('opacity', 0.5);
		//$('#mask').fadeIn(1000);	
		//$('#mask').fadeTo("slow", 0.5);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		$('#dialog').css('top',  winH/2-$('#dialog').height()/2);
		$('#dialog').css('left', winW/2-$('#dialog').width()/2);
	
		//transition effect
		$('#dialog').show();//fadeIn(200); 
	
	//});
}

function cfHideModal() {
	$('#mask').hide();
	$('.window').hide();
}